package com.example.chirdrenserver.Service.Impl;


import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.chirdrenserver.Pojo.entity.Captcha;
import com.example.chirdrenserver.Service.CaptchaService;
import com.example.chirdrenserver.Utils.SedCaptchaUtil;
import com.example.chirdrenserver.properties.CaptchaProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;

/**
 * @Author: Yu
 * @CreateTime: 2025-06-30
 * @Description:
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CaptchaProperties captchaProperties;

    @Override public void createCaptcha(String uuId, HttpServletResponse response) throws IOException {

        if (ObjectUtils.isEmpty(uuId)) throw new IllegalArgumentException("uuid不能为空");
        CircleCaptcha circleCaptcha = SedCaptchaUtil.CreateCircleCaptcha(captchaProperties.getWidth(), captchaProperties.getHigh(), captchaProperties.getCodeCount(), captchaProperties.getLineCount(), uuId);
        String code = circleCaptcha.getCode();
        String format = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        String expireTime = LocalDateTime.now().plusMinutes(5).format(dateTimeFormatter);
        Captcha captcha = new Captcha(uuId, code, expireTime);
        String key = "captcha:" + uuId;
        redisTemplate.opsForValue().set(key, captcha);
        // 设置过期时间（假设expireTime是Unix时间戳）
        response.setContentType("image/png");//告诉浏览器输出内容为图片
        response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        ServletOutputStream out = response.getOutputStream();
        out.write(circleCaptcha.getImageBytes());

    }

    @Override public Captcha getCaptcha(String uuid) {
        String key = "captcha:" + uuid;
        Object temp =redisTemplate.opsForValue().get(key);
        ObjectMapper mapper = new ObjectMapper();
        Captcha captcha = mapper.convertValue(temp, Captcha.class);
        // 自动反序列化为Captcha对象
        return (captcha) ;
    }

    public void deleteCaptcha(String userId) {
        String key = "captcha:" + userId;
        redisTemplate.delete(key);
    }
}
